<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use App\Models\Article;
use App\Models\CheckUserProfile;
use App\Models\Company;
use App\Models\UserProfile;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;

class ReplaceDomain extends Command
{
    const REPLACE_COLUMN = [
        Article::class => [
            'content',
        ],
        Company::class => [
            'brief',
        ],
        UserProfile::class => [
            'vaccination_screenshot_path',
        ],
        CheckUserProfile::class => [
            'vaccination_screenshot_path',
        ],
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'domain:replace {oldDomain} {newDomain}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更换平台后端域名';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $oldDomain = $this->argument('oldDomain');
        $newDomain = $this->argument('newDomain');
        foreach (self::REPLACE_COLUMN as $modelPath => $columns) {
            /** @var Model $model */
            $model = new $modelPath();
            foreach ($columns as $column) {
                $columnInfos = $model::query()->select('id', $column)->get()->toArray();
                if (empty($columnInfos)) {
                    continue;
                }
                foreach ($columnInfos as $columnInfo) {
                    $id = $columnInfo['id'];
                    $content = $columnInfo[$column];
                    $newInfo = str_replace($oldDomain, $newDomain, $content);
                    $model::query()->where('id', $id)->update([
                        $column => $newInfo,
                    ]);
                }
            }
        }
        $this->info(sprintf('replace %s to %s successfully', $oldDomain, $newDomain));
        return 0;
    }
}
